const API = require('../../utils/api')
const pathUrl = require('../../utils/common')
Page({
  data: {
    categories: [
      { id: 0, name: '全部', icon: '📋' },
      { id: 1, name: '球拍', icon: '🎾' },
      { id: 2, name: '网球', icon: '🏀' },
      { id: 3, name: '服装', icon: '👕' },
      { id: 4, name: '鞋类', icon: '👟' },
      { id: 5, name: '配件', icon: '🎒' },
      { id: 6, name: '其他', icon: '🧰' }
    ],
    products: [],
    currentCategory: '',
    searchKey: '',
    pageNum: 1, // 当前页码
    pageSize: 10, // 每页显示数量
    hasMore: false, // 是否还有更多数据
    triggered:false
  },

  onLoad() {
    this.getList();
  },
  onSearch(e){
    const value = e.detail.value
    this.setData({ 
      searchKey: value,
      pageNum:1,
    })
    this.getList()
  },
  onRefresh(){
    this.setData({
      pageNum:1,
      hasMore:false
    })
    this.getList()
    this.setData({
      triggered:false
    })
  },
  async onReachBottom(){
    if (!this.data.hasMore){
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none'
      });
      return;
    }
    let tempList = this.data.products;
    this.setData({
      pageNum:this.data.pageNum+1,
    })
   await this.getList()
    this.setData({
      products:[...tempList,...this.data.products]
    })
  },
  //查询数据列表
  async getList(){
    wx.showLoading({
      title: '搜索中...',
      mask: true
    });
    let res = await API.productList({status:'1',productType:this.data.currentCategory,productName:this.data.searchKey,pageSize:this.data.pageSize,pageNum:this.data.pageNum})
    for(let i =0;i<res.records.length;i++){
      res.records[i].image = pathUrl+res.records[i].image 
    }
    this.setData({ 
      products: res.records, 
      hasMore:res.pages>this.data.pageNum?true:false,
    });
    wx.hideLoading()
  },

  switchCategory(e) {
    const category = e.currentTarget.dataset.item
    this.setData({ 
      currentCategory: category.name=='全部'?'':category.name, 
      pageNum: 1,
      hasMore: false
    })
    this.getList()
  },

  goToProductDetail(e) {
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?item=${JSON.stringify(item)}`
    })
  },
  
  onShareAppMessage() {
    return {
      title: '网球装备商城 - 专业网球用品',
      path: '/pages/shop/shop',
      imageUrl: '/images/share-shop.jpg'
    }
  }
})